using System.Diagnostics.CodeAnalysis;
using System.Web;
using AngleSharp.Dom;
using AngleSharp.Html.Parser;
using Microsoft.Extensions.Logging;
using OpenQA.Selenium;
using OpenQA.Selenium.Edge;
using Wechat.Service.Filter;

namespace Wechat.Service.Browser;

public class BrowserService : IBrowserService
{
    private readonly ILogger<BrowserService> _logger;
    private readonly IFilterService _filterService;

    public BrowserService(ILogger<BrowserService> logger, IFilterService filterService)
    {
        _logger = logger;
        _filterService = filterService;
    }

    public async Task<string> GetHtmlByUrl(string url)
    {
        await DownLoadPageAsync(url);
        return "";
    }

    public async Task<(string fileName, string html)> DownLoadPageAsync(string url)
    {
        // System.Console.WriteLine(url);
        var options = new EdgeOptions();
        // options.AddArgument("headless");
        // 规避被检测到的风险
        // options.AddExcludedArgument("enable-automation");
        // 初始化 Edge 驱动器
        // EdgeDriverService service = EdgeDriverService.CreateDefaultService();
        // service.HideCommandPromptWindow = true; // 隐藏命令提示符窗口
        IWebDriver driver = new EdgeDriver(options);
        driver.Navigate().GoToUrl(url);
        driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(5000);
        var html = driver.PageSource;
        // 创建HTML解析器
        var parser = new HtmlParser();
        // 解析HTML内容
        var document = await parser.ParseDocumentAsync(html);
        // 查找id为"name"的h1元素
        var h1Element = document.QuerySelector("#activity-name");
        var articleTitle = h1Element?.TextContent.ToString().Replace("/", "_") ?? "";
        // id = publish_time
        var publishTime = document.QuerySelector("#publish_time")?.TextContent.ToString() ?? DateTime.Now.ToString();
        var newPublishTime = DateTime.Parse(publishTime).ToString("yyyyMMdd_HHmmss");
        var fileName = $"{newPublishTime.Trim()}_{articleTitle.Trim()}.html";
        // var publicAccountId = (document.Body?.TextContent.ToString().Split("var biz = \"")[1].Substring(0, 14)) ?? Guid.NewGuid().ToString();
        driver.Quit();
        return (fileName, html);
    }

    public async Task<(string folderName, string fileName, string html)> DownLoadPageByGetRequest(string url)
    {
        var body = await this.DownLoadRawPageByGetRequest(url);

        // 创建HTML解析器
        var parser = new HtmlParser();
        // 解析HTML内容
        var document = await parser.ParseDocumentAsync(body);
        // 查找id为"name"的h1元素
        var h1Element = document.QuerySelector("#activity-name");
        var articleTitle = h1Element?.TextContent.ToString().Replace("/", "_") ?? "";
        var createTime = body.Split(@"var createTime = '").LastOrDefault()?.ToString().Substring(0, 16);
        System.Console.WriteLine(createTime);
        if (string.IsNullOrEmpty(createTime))
            createTime = DateTime.Now.ToString();
        // System.Console.WriteLine(createTime);
        var publishTime = DateTime.Parse(createTime).ToString("yyyyMMdd_HHmmss");
        var nickName = body.Split(@"var nickname = htmlDecode(").LastOrDefault()?.ToString().Substring(1, 30).Split('"').FirstOrDefault();
        var fileName = $"{publishTime.Trim()}_{nickName}_{articleTitle.Trim()}.html";
        // System.Console.WriteLine(body.Split(@"var biz = ")[2].ToString().Substring(1, 16));
        var biz = body.Split(@"var biz = ")[2].ToString().Substring(1, 16);
        // System.Console.WriteLine(fileName);
        // System.Console.WriteLine(document.QuerySelector("#js_content")?.OuterHtml);
        // var content = document.QuerySelector("#js_content")?.OuterHtml ?? "";

        document.QuerySelector("#js_content")?.SetAttribute("style", "visibility: visible;");

        var content = @$"<!DOCTYPE html><html><head></head><body>{document.QuerySelector("#js_content")?.OuterHtml ?? ""}</body></html>";
        // System.Console.WriteLine(articleTitle);
        // System.Console.WriteLine(publishTime);
        return (biz, fileName, content);
    }

    public async Task<string> DownLoadRawPageByGetRequest(string url)
    {
        var client = new HttpClient();
        var request = new HttpRequestMessage
        {
            Method = HttpMethod.Get,
            RequestUri = new Uri(url),
            Headers =
            {
                {
                    "User-Agent",
                    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 Edg/124.0.0.0"
                }
            }
        };
        using var response = await client.SendAsync(request);
        response.EnsureSuccessStatusCode();
        var body = await response.Content.ReadAsStringAsync();
        return body;
    }

    public async Task<(string body, string title, bool originalFlag)> DownLoadModifyPageByGetRequest(string url)
    {
        var client = new HttpClient();
        var request = new HttpRequestMessage
        {
            Method = HttpMethod.Get,
            RequestUri = new Uri(url),

            Headers =
            {
                {
                    "User-Agent",
                    @"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0"
                },
                // cookie需要经常替换,否则无法访问
                {
                    "Cookie",
                    "_qimei_q36=; _qimei_h38=b8adec6b92c108fed27e77a002000008e18519; ptcz=d8c5da24832349600236fb79c067637735acfb4f734f0568ef5e005a17d508a5; ua_id=Z0wM42FiH1ZytEYcAAAAAJEnQcIchzVfn-SDQZprZk0=; pgv_pvid=7684287875; mm_lang=zh_CN; suid=user_0_CptZNA4RxJWA1; _qimei_fingerprint=af9af71f6913167c78603752c3d6f100; _ga=GA1.2.2142936103.1738759999; _ga_8YVFNWD1KC=GS1.2.1738759998.1.0.1738759998.0.0.0; eas_sid=P1m773B8d942b5U5r8V8v108s6; fqm_pvqid=8dacc7db-ec4c-4faa-8a72-65461ec9aaee; omgid=0_CptZNA4RxJWA1; yyb_muid=07F7CD7191AA69BF08C0D9E09003688A; wxuin=52851319600173; _qimei_uuid42=1971e132f2b100265fe1165ed038ba9048bf0f49df; RK=ta94IGcfZr; _clck=3906292091|1|fyq|0; xid=2a6807f7708b4b4bb30b8f943adb181d; _hp2_id.1405110977=%7B%22userId%22%3A%221959381983892512%22%2C%22pageviewId%22%3A%222855723399794821%22%2C%22sessionId%22%3A%22616406155987143%22%2C%22identity%22%3Anull%2C%22trackerVersion%22%3A%224.0%22%7D; rewardsn=; poc_sid=HJ7Bs2ijwsDfjdpz2u9an89O85J5TgDG_yhoHE5k; wxtokenkey=777"
                },
                { "Origin", "https://mp.weixin.qq.com" },
                { "Sec-Fetch-Mode", "navigate" },
                { "Sec-Fetch-Site", "same-origin" },
                { "X-Requested-With", "XMLHttpRequest" },
            }
        };

        using var response = await client.SendAsync(request);
        response.EnsureSuccessStatusCode();
        var body = await response.Content.ReadAsStringAsync();
        var document = await new HtmlParser().ParseDocumentAsync(body);

        // 此内容因违规无法查看
        if (document.Body.Text().Contains("此内容因违规无法查看"))
        {
            return ("此内容因违规无法查看", string.Empty, false);
        }

        bool isHasJsContent = await _filterService.HasJsContent(body);
        string articleTitle = await _filterService.GetArticleTitle(body);
        bool isOriginal = await _filterService.GetOrignalStatus(body);

        if (!isHasJsContent || string.IsNullOrEmpty(articleTitle))
        {
            return (string.Empty, string.Empty, false);
        }

        string newBody = _filterService.ReplaceHtmlHref(body);
        string newBody2 = await _filterService.DeleteScrpitsAsync(newBody);
        return (newBody2, articleTitle, isOriginal);
    }
}
